/**
 * 
 */
package org.hehui.supervisorysystem.ui.viewpart.SitoyUserManagerViewPart;


import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;


import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Status;
import org.eclipse.core.runtime.jobs.IJobChangeEvent;
import org.eclipse.core.runtime.jobs.Job;
import org.eclipse.core.runtime.jobs.JobChangeAdapter;
import org.eclipse.jface.action.Action;
import org.eclipse.jface.action.IToolBarManager;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.ISelectionChangedListener;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.viewers.SelectionChangedEvent;
import org.eclipse.jface.viewers.TableViewer;
import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.ScrolledComposite;
import org.eclipse.swt.events.KeyAdapter;
import org.eclipse.swt.events.KeyEvent;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Combo;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Event;
import org.eclipse.swt.widgets.FileDialog;
import org.eclipse.swt.widgets.Group;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Listener;
import org.eclipse.swt.widgets.Table;
import org.eclipse.swt.widgets.TableColumn;
import org.eclipse.swt.widgets.TableItem;
import org.eclipse.swt.widgets.Text;
import org.eclipse.ui.part.ViewPart;
import org.eclipse.ui.plugin.AbstractUIPlugin;
import org.hehui.supervisorysystem.sql.entity.Users;
import org.hehui.supervisorysystem.util.HibernateSessionFactory;
import org.hehui.supervisorysystem.util.IAppConstants;
import org.hehui.supervisorysystem.util.IImageKey;
import org.hehui.supervisorysystem.util.SWTResourceManager;
import org.hibernate.CacheMode;
import org.hibernate.Query;
import org.hibernate.ScrollMode;
import org.hibernate.ScrollableResults;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.AnnotationConfiguration;

/**
 * @author 贺辉
 * 
 */
public class SitoyUserManagerViewPart extends ViewPart {

	// boolean isAdmin = false;

	private Text passwordText;
	private Combo deptCombo;
	private Text nameText;
	private Text idText;

	private TableViewer tableViewer;

	private Action queryAction, clearTextAction, exportDataAction,
			firstPageAction, prePageAction, nextPageAction, lastPageAction;

	/**
	 * 
	 */
	public SitoyUserManagerViewPart() {
		// TODO Auto-generated constructor stub
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * org.eclipse.ui.part.WorkbenchPart#createPartControl(org.eclipse.swt.widgets
	 * .Composite)
	 */
	@Override
	public void createPartControl(Composite parent) {
		createViewPart(parent);
		createToolBarButtons();

	}

	private void createViewPart(Composite parent) {

		// 带滚动条的容器
		ScrolledComposite sc = new ScrolledComposite(parent, SWT.BORDER
				| SWT.H_SCROLL | SWT.V_SCROLL);
		sc.setShowFocusedControl(true);
		sc.setExpandHorizontal(true);
		sc.setExpandVertical(true);
		// 组件容器
		Composite composite = new Composite(sc, SWT.NONE);
		composite.setLayout(new GridLayout());

		final Composite parentInfoComposite = new Composite(composite, SWT.NONE);
		final GridData gd_parentInfoComposite = new GridData(SWT.FILL,
				SWT.CENTER, true, false);
		gd_parentInfoComposite.heightHint = 90;
		gd_parentInfoComposite.widthHint = 843;
		parentInfoComposite.setLayoutData(gd_parentInfoComposite);
		final GridLayout gridLayout_2 = new GridLayout();
		parentInfoComposite.setLayout(gridLayout_2);

		final Group userInfoGroup = new Group(parentInfoComposite, SWT.NONE);
		final GridData gd_userInfoGroup = new GridData(SWT.FILL, SWT.FILL,
				true, true);
		gd_userInfoGroup.widthHint = 584;
		gd_userInfoGroup.heightHint = 188;
		userInfoGroup.setLayoutData(gd_userInfoGroup);
		final GridLayout gridLayout = new GridLayout();
		userInfoGroup.setLayout(gridLayout);
		userInfoGroup.setText("User Info");

		final Composite userInfoComposite = new Composite(userInfoGroup,
				SWT.NONE);
		final GridData gd_userInfoComposite = new GridData(SWT.FILL, SWT.FILL,
				true, true);
		gd_userInfoComposite.heightHint = 174;
		gd_userInfoComposite.widthHint = 520;
		userInfoComposite.setLayoutData(gd_userInfoComposite);
		final GridLayout gridLayout_1 = new GridLayout();
		gridLayout_1.numColumns = 8;
		userInfoComposite.setLayout(gridLayout_1);

		final Label idLabel = new Label(userInfoComposite, SWT.NONE);
		idLabel.setFont(SWTResourceManager.getFont("Sans", 10, SWT.NONE));
		idLabel.setLayoutData(new GridData(40, SWT.DEFAULT));
		idLabel.setText("ID:");

		idText = new Text(userInfoComposite, SWT.BORDER);
		idText.setFont(SWTResourceManager.getFont("Sans", 12, SWT.NONE));
		final GridData gd_idText = new GridData(SWT.FILL, SWT.CENTER, true,
				false);
		gd_idText.widthHint = 120;
		gd_idText.minimumWidth = 100;
		idText.setLayoutData(gd_idText);

		final Label passwordLabel = new Label(userInfoComposite, SWT.NONE);
		passwordLabel.setFont(SWTResourceManager.getFont("Sans", 10, SWT.NONE));
		passwordLabel.setText("Password:");

		passwordText = new Text(userInfoComposite, SWT.READ_ONLY | SWT.BORDER);
		passwordText.setFont(SWTResourceManager.getFont("Sans", 12, SWT.BOLD));
		final GridData gd_passwordText = new GridData(SWT.FILL, SWT.CENTER,
				true, false);
		gd_passwordText.minimumWidth = 180;
		gd_passwordText.widthHint = 196;
		passwordText.setLayoutData(gd_passwordText);

		final Label nameLabel = new Label(userInfoComposite, SWT.NONE);
		nameLabel.setFont(SWTResourceManager.getFont("Sans", 10, SWT.NONE));
		final GridData gd_nameLabel = new GridData(62, SWT.DEFAULT);
		nameLabel.setLayoutData(gd_nameLabel);
		nameLabel.setText("Name:");

		nameText = new Text(userInfoComposite, SWT.BORDER);
		nameText.setFont(SWTResourceManager.getFont("Sans", 12, SWT.NONE));
		final GridData gd_nameText = new GridData(SWT.FILL, SWT.CENTER, true,
				false);
		gd_nameText.widthHint = 60;
		gd_nameText.minimumWidth = 60;
		nameText.setLayoutData(gd_nameText);

		final Label deptLabel = new Label(userInfoComposite, SWT.NONE);
		deptLabel.setFont(SWTResourceManager.getFont("Sans", 10, SWT.NONE));
		final GridData gd_deptLabel = new GridData(SWT.CENTER, SWT.CENTER,
				false, false);
		gd_deptLabel.widthHint = 52;
		deptLabel.setLayoutData(gd_deptLabel);
		deptLabel.setText("Dept:");

		deptCombo = new Combo(userInfoComposite, SWT.READ_ONLY);
		deptCombo.setFont(SWTResourceManager.getFont("Sans", 12, SWT.NONE));
		deptCombo.setItems(new String[] { "All", "Account", "Cost", "Custom",
				"HR", "Marker", "PDS", "PG", "Plan", "PMC", "Purchase", "QC",
				"Sales", "Sample", "Secretary", "Ship", "Shop", "WHouse" });
		deptCombo.select(0);
		final GridData gd_deptCombo = new GridData(SWT.FILL, SWT.CENTER, true,
				false);
		gd_deptCombo.minimumWidth = 110;
		gd_deptCombo.widthHint = 112;
		deptCombo.setLayoutData(gd_deptCombo);

		tableViewer = new TableViewer(composite, SWT.FULL_SELECTION | SWT.MULTI
				| SWT.H_SCROLL | SWT.V_SCROLL | SWT.BORDER);
		tableViewer.setUseHashlookup(true);
		tableViewer
				.addSelectionChangedListener(new ISelectionChangedListener() {
					@Override
					public void selectionChanged(SelectionChangedEvent event) {
						IStructuredSelection selection = (IStructuredSelection) event
								.getSelection();
						if (selection.getFirstElement() instanceof Users) {
							Users sitoyUser = (Users) selection
									.getFirstElement();
							idText.setText(sitoyUser.getUserid().trim());
							passwordText.setText(sitoyUser.getCpassword());
							nameText.setText(sitoyUser.getCname());
							// deptCombo.select(deptCombo.indexOf(sitoyUser.getCgroup()));

						}

					}

				});

		// 创建表格列
		final Table table = tableViewer.getTable();
		// table.setLayoutData(new GridData(GridData.FILL_BOTH));
		table.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));
		table.setHeaderVisible(true);

		final TableColumn idColumn = new TableColumn(table, SWT.LEFT);
		idColumn.setText("ID");
		idColumn.setWidth(200);

		final TableColumn userNameTableColumn = new TableColumn(table, SWT.LEFT);
		userNameTableColumn.setText("Name");
		userNameTableColumn.setWidth(200);

		final TableColumn passwordTableColumn = new TableColumn(table, SWT.LEFT);
		passwordTableColumn.setText("Password");
		passwordTableColumn.setWidth(200);

		final TableColumn deptTableColumn = new TableColumn(table, SWT.LEFT);
		deptTableColumn.setText("Dept");
		deptTableColumn.setWidth(100);

		final TableColumn eEmailTableColumn = new TableColumn(table, SWT.LEFT);
		eEmailTableColumn.setText("Email");
		eEmailTableColumn.setWidth(250);

		// final TableColumn iEmailTableColumn = new
		// TableColumn(table,SWT.RIGHT);
		// iEmailTableColumn.setText("Int Email");
		// iEmailTableColumn.setWidth(250);

		// 设置内容器和标签器
		tableViewer.setContentProvider(new SitoyUserInfoContentProvider());
		tableViewer.setLabelProvider(new SitoyUserInfoLabelProvider());

		// 指定数据提供者
		// tableViewer.setInput(getData("ac", "", ""));
		table.select(0);
		table.setFocus();
		// ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

		// TODO:必须放在最后？？？
		sc.setContent(composite);
		// 以userInfoContainer的初始大小为sc的最小值
		//sc.setMinSize(parentInfoComposite.computeSize(SWT.DEFAULT,SWT.DEFAULT));
		sc.setMinSize(userInfoComposite.computeSize(SWT.DEFAULT,SWT.DEFAULT));
		
		composite.layout();
		
		//事件监听
		Listener listener = new Listener(){
			@Override
			public void handleEvent(Event event) {
				switch (event.type) {
				case SWT.KeyDown:
					if(event.keyCode == SWT.ESC){
						idText.setText("");
						passwordText.setText("");	
						nameText.setText("");
						idText.setFocus();
					}else if(event.keyCode == SWT.CR){
						if((event.stateMask & SWT.CTRL) != 0){
						queryAction.run();
						}
					}
					break;
					

				default:
					break;
				}
	
			}
		};
		
		idText.addListener(SWT.KeyDown, listener);
		passwordText.addListener(SWT.KeyDown, listener);
		nameText.addListener(SWT.KeyDown, listener);
		deptCombo.addListener(SWT.KeyDown, listener);
		table.addListener(SWT.KeyDown, listener);

		

	}

	@SuppressWarnings("unused")
	private Object getData(String id, String name, String dept) {

		List<Users> list = new ArrayList<Users>();

		Session session = HibernateSessionFactory
				.getSession("hibernate.mssqlserver.cfg.xml");

		Query query = session
				.getNamedQuery("org.hehui.memory.SitoyUserManagerViewPart.getSitoyUser");
		query.setString("id", "%" + id + "%");
		query.setString("name", "%" + name + "%");
		query.setString("dept", "%" + dept + "%");

		// 使用数据库游标提高性能
		ScrollableResults result = query.setCacheMode(CacheMode.IGNORE).scroll(
				ScrollMode.FORWARD_ONLY);
		while (result.next()) {
			Users sitoyUser = (Users) result.get(0);
			if (sitoyUser != null) {
				list.add(sitoyUser);
			}
		}

		/*
		 * for (Iterator iterator = query.iterate(); iterator.hasNext();) {
		 * SitoyUsers sitoyUser = (SitoyUsers) iterator.next();
		 * 
		 * //TODO:必须调用一次User的属性，TableViewer中才能显示数据！？？？？？？？？？？？？？
		 * System.out.println
		 * ("-----------------------------------------------");
		 * System.out.println(sitoyUser.getId()+"-----"+sitoyUser.getCname());
		 * System
		 * .out.println("-----------------------------------------------");
		 * 
		 * if (sitoyUser != null) { list.add(sitoyUser); }
		 * 
		 * }
		 */

		HibernateSessionFactory.closeSession();
		System.out.println("--------------------------" + list.size()
				+ " Rows Returned" + "--------------------------");
		return list;

	}

	private void query(final String id, final String name, final String dept) {
		exportDataAction.setEnabled(false);

		final List<Users> list = new ArrayList<Users>();

		Job job = new Job("Querying Database") {
			@Override
			protected IStatus run(IProgressMonitor monitor) {
				monitor.beginTask("Querying Database",IProgressMonitor.UNKNOWN);
				monitor.subTask("Creating Hibernate Configuration....");
				

				// SessionFactory sf_msSQLServer = new Configuration().configure("hibernate.mssqlserver.cfg.xml").buildSessionFactory();
				SessionFactory sf_msSQLServer = new AnnotationConfiguration()
						.configure("hibernate.mssqlserver.cfg.xml")
						.buildSessionFactory();

				Session session = sf_msSQLServer.openSession();

				// Session session = HibernateSessionFactory
				// .getSession("hibernate.mssqlserver.cfg.xml");

				Query query = session
						.getNamedQuery("org.hehui.supervisorysystem.SitoyUserManagerViewPart.getSitoyUser");
				query.setString("id", "%" + id + "%");
				query.setString("name", "%" + name + "%");
				query.setString("dept", "%" + dept + "%");

				// 使用数据库游标提高性能
				ScrollableResults result = query.setCacheMode(CacheMode.IGNORE)
						.scroll(ScrollMode.FORWARD_ONLY);
				while (result.next()) {
					Users sitoyUser = (Users) result.get(0);
					if (sitoyUser != null) {
						list.add(sitoyUser);
					}
				}

				/*
				 * for (Iterator iterator = query.iterate();
				 * iterator.hasNext();) { SitoyUsers sitoyUser = (SitoyUsers)
				 * iterator.next();
				 * 
				 * //TODO:必须调用一次User的属性，TableViewer中才能显示数据！？？？？？？？？？？？？？
				 * System.out
				 * .println("-----------------------------------------------");
				 * System
				 * .out.println(sitoyUser.getId()+"-----"+sitoyUser.getCname());
				 * System
				 * .out.println("-----------------------------------------------"
				 * );
				 * 
				 * if (sitoyUser != null) { list.add(sitoyUser); }
				 * 
				 * }
				 */

				// HibernateSessionFactory.closeSession();
				session.close();
				System.out.println("--------------------------" + list.size()
						+ " Rows Returned" + "--------------------------");
				// return list;

				monitor.done();
				return Status.OK_STATUS;
			}

		};

		job.addJobChangeListener(new JobChangeAdapter() {
			public void done(IJobChangeEvent event) {
				final boolean isSucess = event.getResult().isOK();
				Display.getDefault().asyncExec(new Runnable() {
					@Override
					public void run() {
						if (isSucess) {
							passwordText.setText("");
							tableViewer.getTable().clearAll();
							tableViewer.refresh();
							tableViewer.setInput(list);
							tableViewer.getTable().setFocus();
							tableViewer.getTable().deselectAll();
							exportDataAction.setEnabled(true);
						} else {
							MessageDialog.openError(null, "Error",
									"Error occurred!");
						}

					}

				});
			}
		});

		job.setUser(true);
		job.setPriority(Job.SHORT);
		job.schedule();

	}

	private void doExportDataJob(final String fileName) {
		final HSSFWorkbook wb = new HSSFWorkbook();
		final HSSFSheet sheet = wb.createSheet("Users");
		Job job = new Job("Exporting Data") {
			@Override
			protected IStatus run(IProgressMonitor monitor) {

				monitor.beginTask("Exporting Data", IProgressMonitor.UNKNOWN);

				monitor.subTask("Retrieving ....");
				List<Users> list = (List<Users>) tableViewer.getInput();
				
				int count = list.size();

				monitor.subTask("Exporting....");
				int curRow = 0;
				for (int i = 0; i < count; i++) {
					Users sitoyUser = (Users) list.get(i);

					if (sitoyUser != null) {
						HSSFRow row = sheet.createRow(curRow);
						HSSFCell cell = row.createCell(0);

						cell.setCellValue(sitoyUser.getUserid());
						HSSFCell cell1 = row.createCell(1);
						cell1.setCellValue(sitoyUser.getCname());

						HSSFCell cell2 = row.createCell(2);
						cell2.setCellValue(sitoyUser.getCpassword());

						HSSFCell cell3 = row.createCell(3);
						cell3.setCellValue(sitoyUser.getCgroup());

						HSSFCell cell4 = row.createCell(4);
						cell4.setCellValue(sitoyUser.getMail());

					}
					curRow++;
				}

				monitor.done();
				queryAction.setEnabled(true);

				return Status.OK_STATUS;
			}

		};

		job.addJobChangeListener(new JobChangeAdapter() {
			public void done(IJobChangeEvent event) {
				final boolean isSucess = event.getResult().isOK();
				Display.getDefault().asyncExec(new Runnable() {
					@Override
					public void run() {
						if (isSucess) {
							try {
								FileOutputStream o = new FileOutputStream(
										fileName);
								try {
									wb.write(o);
								} catch (IOException e) {
									// TODO Auto-generated catch block
									e.printStackTrace();
								}
								try {
									o.close();
								} catch (IOException e) {
									// TODO Auto-generated catch block
									e.printStackTrace();
								}
							} catch (FileNotFoundException e) {
								// TODO Auto-generated catch block
								e.printStackTrace();
							}
						} else {
							MessageDialog.openError(null, "Error",
									"Error occurred while exporting data!");
						}

					}

				});
			}
		});

		job.setUser(true);
		job.setPriority(Job.SHORT);
		job.schedule();
	}

	private void exportData() {
		queryAction.setEnabled(false);

		int count = tableViewer.getTable().getItemCount();
		if (count <= 0) {
			MessageDialog.openError(null, "Error", "Empty Data Table!");
			return;
		}

		FileDialog openFileDlg = new FileDialog(getViewSite().getShell(),
				SWT.SAVE);
		openFileDlg.setText("Save File To");
		openFileDlg.setFilterNames(new String[] { "XLS(*.xls)", "*.*" });
		openFileDlg.setFilterExtensions(new String[] { "*.xls", "*.*" });
		String fileName = openFileDlg.open();

		if (fileName == null) {
			// MessageDialog.openError(getViewSite().getShell(),
			// "None Selected", "None Selected");
			queryAction.setEnabled(true);
			return;
		} else {
			//int selectionIndices[] = tableViewer.getTable().getSelectionIndices();
			//System.out.println(String.valueOf(selectionIndices.length));
			//MessageDialog.openInformation(null, "selectionIndices.length", String.valueOf(selectionIndices.length));
		 	
			doExportDataJob(fileName/* , "UTF-8" */);
		}

	}

	private void createToolBarButtons() {
		queryAction = new Action("Query", AbstractUIPlugin
				.imageDescriptorFromPlugin(IAppConstants.APPLICATION_ID,
						IImageKey.QUERY_DATA)) {
			public void run() {
				String dept = deptCombo.getText();
				if (dept.contains("All")) {
					dept = "";
				}

				query(idText.getText(), nameText.getText(), dept);

				// tableViewer.getTable().clearAll();
				// tableViewer.setInput(getData(idText.getText(),
				// nameText.getText(), dept));
			}
		};
		//queryAction.setAccelerator(SWT.F5);

		clearTextAction = new Action("Clear", AbstractUIPlugin
				.imageDescriptorFromPlugin(IAppConstants.APPLICATION_ID,
						IImageKey.CLEAR_TEXT)) {
			public void run() {
				idText.setText("");
				passwordText.setText("");
				nameText.setText("");
				tableViewer.getTable().deselectAll();
			}
		};
		//clearTextAction.setAccelerator(SWT.F8);

		exportDataAction = new Action("Export", AbstractUIPlugin
				.imageDescriptorFromPlugin(IAppConstants.APPLICATION_ID,
						IImageKey.EXPORT_DATA)) {
			public void run() {
				exportData();
			}
		};
		//exportDataAction.setAccelerator(SWT.F9);

		IToolBarManager toolBarMgr = getViewSite().getActionBars()
				.getToolBarManager();
		toolBarMgr.add(queryAction);
		toolBarMgr.add(clearTextAction);
		toolBarMgr.add(exportDataAction);
		exportDataAction.setEnabled(false);
	}

	@Override
	public void setFocus() {
		// TODO Auto-generated method stub

	}

}
